<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>allSettled-方法</title>
</head>
<style>
    body {
        width: 100%;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-flow: column;
    }

    button {
        background-color: skyblue;
        color: hotpink;
        padding: 5px;
        width: 80px;
        height: 30px;
        font-size: 16px;
        border: none;
        box-shadow: 0 0 2px grey;
        border-radius: 3%;
        transition: all 0.2s linear;
    }

    button:hover {
        transform: scale(1.1);
        background-color: dodgerblue;
        color: palegreen;
        box-shadow: 0 0 5px grey;
    }

    div {
        width: 300px;
        height: 300px;
        background-color: black;
        color: greenyellow;
        font-size: 18px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 50px;
    }
</style>
<body>
<div></div>
<button>确认</button>
<script>
        // allSettled-方法  用来确定一组异步的操作是否都结束了(不管是否成功还是失败)

    const btn = document.getElementsByTagName('button')[0]
    const box = document.getElementsByTagName('div')[0]

    //封装一个AJAX函数
    function ajax(url) {
        return new Promise((resolve, reject) => {
            //点击按钮时发送ajax请求
            btn.addEventListener('click', () => {
                // ajax实例对象
                let xhr = new XMLHttpRequest()
                // 打开请求
                xhr.open('GET', url)
                //发送请求
                xhr.send()
                // 接收服务器响应的响应体
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.responseText)
                        reject(xhr.statusText)
                    }
                }
            })
        })
    }

    Promise.allSettled([
        ajax('http://localhost:9000/index'),//成功的ajax请求
        ajax('http://localhost:9000/index1')//失败的ajax请求

    ]).then(value => {
        // 过滤成功和失败的两种情况
        let success=value.filter(item=>item.status==='fulfilled')
        console.log(success)    //过滤成功
        box.innerHTML=success[0].value
        //let error= value.filter(item=>item.status==='rejected')
        // console.log(error) //过滤失败
    }).catch(reason => {
        console.log(reason)
    })
</script>
</body>
</html>